#include "tls_connection.h"

int client_init_connection(TCP_CONNECTION *conn) {
    struct sockaddr_in s_addr;
    int err = 0; 

    err = sock_create_kern(&init_net, AF_INET, SOCK_STREAM, IPPROTO_TCP, &conn->sock);
    if (err < 0) {
        printk("client:socket create error!\n");
        return err;
    }
    printk("client: socket create ok!\n");
    memset(&s_addr, 0, sizeof(s_addr));
    s_addr.sin_family = AF_INET;
    s_addr.sin_port = htons(port_num);
    s_addr.sin_addr.s_addr = in_aton("127.0.0.1");
    err = conn->sock->ops->connect(conn->sock, (struct sockaddr *)&s_addr, sizeof(s_addr), 0);
    if (err != 0) {
        printk("client: connect error!\n");
        return err;
    }
    printk("client: connect ok!\n");
    return 0;
}

int server_init_listen(TCP_CONNECTION *conn) {
    struct sockaddr_in s_addr;  
    int ret = 0;  
    /*create a socket*/  
    ret = sock_create_kern(&init_net, AF_INET, SOCK_STREAM, IPPROTO_TCP, &conn->sock);  

    if (ret < 0) {  
        printk("server:socket_create error!\n");  
        goto err;
    } else {
        printk("server:socket_create ok!\n");  
    }  

    sock_set_reuseaddr(conn->sock->sk);
    sock_set_reuseport(conn->sock->sk);

    memset(&s_addr,0,sizeof(s_addr));  
    s_addr.sin_family = AF_INET;  
    s_addr.sin_port = htons(port_num);  
    s_addr.sin_addr.s_addr= in_aton("0.0.0.0");  
    /*bind the socket*/  
    ret = kernel_bind(conn->sock, (struct sockaddr *)&s_addr, sizeof(struct sockaddr_in));  

    if (ret < 0) {  
        printk("server: bind error\n");  
        goto err; 
    }  
    printk("server:bind ok!\n");  

    ret = kernel_listen(conn->sock, 64);  
    if (ret < 0) {  
        printk("server: listen error\n");  
        goto err;  
    }  
    printk("server:listen ok!\n");  
    return 0;
err: 
    if (conn->sock) {
        sock_release(conn->sock);
    }
    return -1;
}
